import { defineStore } from 'pinia'
import {
  getPageListData,
  addPage,
  deletePageById,
  editPage,
  editStatus
} from '@/service/main/system'
import { MessagePlugin } from 'tdesign-vue-next'
import useCommonStore from './common'

const pageToActionMap: Record<string, string[]> = {
  dept: ['getAllDeptAction']
}

interface ISystemState {
  Loading: boolean
  user: any[]
  dept: any[]
  client: any[]
  userPagination: any
  deptPagination: any
  clientPagination: any
}

const useSystemStore = defineStore('system', {
  state: (): ISystemState => ({
    Loading: false,
    user: [],
    dept: [],
    client: [],
    userPagination: {},
    deptPagination: {},
    clientPagination: {}
  }),
  actions: {
    // 获取
    async getPageListAction(pageName: string, queryInfo: any) {
      this.Loading = true
      const res = await getPageListData(pageName, queryInfo)
      // @ts-ignore
      this.$state[`${pageName}`] = res.data
      console.log(res.data)

      // @ts-ignore
      this.$state[`${pageName}Pagination`] = res.meta.pagination
      this.Loading = false
    },

    // 新增
    async addPageAction(pageName: string, addInfo: any, queryInfo: any) {
      const res = await addPage(pageName, addInfo)
      this.getPageListAction(pageName, queryInfo)
      this.getCommonInfoAction(pageName)
      MessagePlugin.success(res.message)
    },

    // 编辑
    async editPageAction(pageName: string, id: number, editinfo: any, queryInfo: any) {
      const res = await editPage(pageName, id, editinfo)
      this.getPageListAction(pageName, queryInfo)
      this.getCommonInfoAction(pageName)
      MessagePlugin.success(res.message)
    },

    // 删除
    async deletePageAction(pageName: string, id: number, queryInfo: any) {
      const res = await deletePageById(pageName, id)
      this.getPageListAction(pageName, queryInfo)
      this.getCommonInfoAction(pageName)
      MessagePlugin.success(res.message)
    },

    // 状态
    async editStatusAction(pageName: string, id: number, queryInfo: any) {
      const res = await editStatus(pageName, id)
      this.getPageListAction(pageName, queryInfo)
      this.getCommonInfoAction(pageName)
      MessagePlugin.success(res.message)
    },

    // 重新获取全局数据
    getCommonInfoAction(pageName: string) {
      const commonStore = useCommonStore()
      pageToActionMap[pageName]?.forEach((item) => {
        // @ts-ignore
        commonStore[item]()
      })
    }
  }
})

export default useSystemStore
